﻿#include "chinesehelper.h"

#include "pinyinresource.h"
#include <map>
#include <string>

static bool gInit = false;
static std::map<std::wstring, std::wstring> gChineseMap;

ChineseHelper::ChineseHelper() {

}

ChineseHelper::~ChineseHelper() {

}

void ChineseHelper::initChineseHelper() {
    if(gInit == false) {
        gChineseMap = PinyinResource::getChineseResource();
        gInit = true;
    }
}


wchar_t ChineseHelper::convertToSimplifiedChinese(wchar_t c) {
    if(!gChineseMap.empty()) {
        std::wstring simplifiedChinese = gChineseMap[std::wstring(1,c)];
        if(!simplifiedChinese.empty()) {
            return simplifiedChinese[0];
        }
    }
    return c;
}

wchar_t ChineseHelper::convertToTraditionalChinese(wchar_t c) {
    if(!gChineseMap.empty()) {
        std::wstring simplifiedChinese(1,c);
        std::map<std::wstring, std::wstring>::iterator it = gChineseMap.begin();
        for(;it != gChineseMap.end(); it++) {
            std::wstring &value = it->second;
            if(value == simplifiedChinese) {
                std::wstring key = it->first;
                return key[0];
            }
        }
    }
    return c;
}

std::wstring ChineseHelper::convertToSimplifiedChinese(std::wstring str) {
    std::wstring sb;
    for (int i = 0, len = str.length(); i < len; i++) {
        wchar_t c = str.at(i);
        sb += convertToSimplifiedChinese(c);
    }
    return sb;
}

std::wstring ChineseHelper::convertToTraditionalChinese(std::wstring str) {
    std::wstring sb;
    for (int i = 0, len = str.length(); i < len; i++) {
        wchar_t c = str.at(i);
        sb += convertToTraditionalChinese(c);
    }
    return sb;
}

bool ChineseHelper::isTraditionalChinese(wchar_t c) {
    if(!gChineseMap.empty()) {
        return gChineseMap.find(std::wstring(1,c)) != gChineseMap.end();
    }
    return false;
}

bool ChineseHelper::isChinese(wchar_t c) {
    return L'〇' == c || (c >= 0x4e00 && c <= 0x9fa5);
}

bool ChineseHelper::containsChinese(std::wstring str) {
    for (int i = 0, len = str.length(); i < len; i++) {
        if (isChinese(str.at(i))) {
            return true;
        }
    }
    return false;
}
